 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=4 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> String concatenation does not scale
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='&#043;,append,optimisation,optimization,pitfall,readObject,serialVersionUID,suspend,concatentation,StringBuffer,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>String concatenation does not scale</div>

<div class='main-body'>
 
<br>To build <tt>String</tt>s dynamically, one may use either the <tt>String</tt>
concatenation operator <tt>+</tt> or the <tt>StringBuilder</tt> class.
(If JDK 1.5 is available, <tt><a href="http://java.sun.com/javase/6/docs/api/java/lang/StringBuilder.html">StringBuilder</a></tt>
is generally preferred over <tt><a href="http://java.sun.com/javase/6/docs/api/java/lang/StringBuffer.html">StringBuffer</a></tt>,
since it avoids internal synchronization costs.) In the great majority
of cases, only a few items are concatenated, and either style may be used
freely, according to taste, without concern for performance.
<p>On relatively <i>rare</i> occasions, however, when performing <i>extensive</i> <tt>String</tt>
manipulation, replacing <tt>+</tt> with <tt>StringBuilder.append</tt> is
likely recommended. Compilers often implement concatenation operations
by creating&nbsp; intermediate objects in the background. Such intermediate
objects are not needed by <tt>StringBuilder</tt>.
<p>Cases in which <tt>+</tt> is very likely acceptable :
<ul>
<li>
if concatenating only a small number of items together, then the difference
in relative performance is very small, and possibly not even measurable
(<i>the great majority of use cases of the concatenation operator fall
into this category</i>).</li>

<li>
in branches of code which represent a failure in the system - for example,
a lost database connection, or an invalid method parameter. Since these
branches are very rarely exercised, the speed at which the system fails
is usually not important</li>
</ul>
Here is an illustration of the difference in execution speed between +
and <tt>StringBuilder.append</tt>, when performing many concatenations.
Clearly, even the + operator is quite fast, and the difference is not going
to be noticeable in the great majority of cases encountered in practice.
<p>Example runs (class appears below) :
<p>(Here, <tt><a href="http://java.sun.com/javase/6/docs/technotes/tools/windows/java.html#nonstandard" title="Non-standard options for java interpreter">-Xint</a></tt> turns off the HotSpot compiler. This ensures the
program is always interpreted, and will execute in a uniform environment
from start to finish, without any compilation into native code.)
<p><tt>>java -cp . -Xint AvoidConcatenation 10</tt>
<br><tt>Num iterations: 10</tt>
<br><tt>Task using + operator: 0 milliseconds</tt>
<br><tt>Task using StringBuilder.append: 0 millisecond</tt>
<p><tt>>java -cp . -Xint AvoidConcatenation 100</tt>
<br><tt>Num iterations: 100</tt>
<br><tt>Task using + operator: 10 milliseconds</tt>
<br><tt>Task using StringBuilder.append: 0 milliseconds</tt>
<p><tt>>java -cp . -Xint AvoidConcatenation 1000</tt>
<br><tt>Num iterations: 1000</tt>
<br><tt>Task using + operator: 210 milliseconds</tt>
<br><tt>Task using StringBuilder.append: 0 milliseconds</tt>
<p><tt>>java -cp . -Xint AvoidConcatenation 10000</tt>
<br><tt>Num iterations: 10000</tt>
<br><tt>Task using + operator: 36913 milliseconds</tt>
<br><tt>Task using StringBuilder.append: 10 milliseconds</tt>
<br>
<PRE>


<span class='comment'>/**
* Illustrates the speed difference between + operator and
* StringBuilder.append, when performing many concatenations.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> AvoidConcatenation {

  <span class='comment'>/**
  * Takes a single argument : the number of iterations to perform.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main (String... arguments) {
    fNumIterations = Integer.parseInt(arguments[<span class='literal'>0</span>]);

    <span class='keyword'>long</span> start = System.currentTimeMillis();
    doWithConcatenationOperator();
    <span class='keyword'>long</span> finish = System.currentTimeMillis();

    System.out.println(<span class='literal'>"Num iterations: "</span> + fNumIterations);
    StringBuilder message = <span class='keyword'>new</span> StringBuilder();
    message.append(<span class='literal'>"Task using + operator: "</span>);
    message.append( finish - start );
    message.append(<span class='literal'>" milliseconds"</span>);
    System.out.println(message);

    start = System.currentTimeMillis();
    doWithStringBuilder();
    finish = System.currentTimeMillis();

    message = <span class='keyword'>new</span> StringBuilder(<span class='literal'>"Task using StringBuilder.append: "</span>);
    message.append( finish - start );
    message.append(<span class='literal'>" milliseconds"</span>);
    System.out.println(message);
  }

  <span class='comment'>// PRIVATE //
</span>  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>int</span> fNumIterations;

  <span class='keyword'>private</span> <span class='keyword'>static</span> String doWithConcatenationOperator() {
    String result = <span class='literal'>"start"</span>;
    <span class='keyword'>for</span> (<span class='keyword'>int</span> idx = <span class='literal'>0</span>; idx &lt; fNumIterations; idx++) {
      result = result + <span class='literal'>"blah"</span>;
    }
    <span class='keyword'>return</span> result;
  }

  <span class='keyword'>private</span> <span class='keyword'>static</span> String doWithStringBuilder() {
    StringBuilder result = <span class='keyword'>new</span> StringBuilder(<span class='literal'>"start"</span>);
    <span class='keyword'>for</span> (<span class='keyword'>int</span> idx = <span class='literal'>0</span>; idx &lt; fNumIterations; idx++) {
      result.append(<span class='literal'>"blah"</span>);
    }
    <span class='keyword'>return</span> result.toString();
  }
}
 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicActionc3b3-2.html?Id=55'>Implementing toString</a> <br>
 
  
  <a href='TopicActiondd78-2.html?Id=85'>Time execution speed</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='4'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=4 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
